import { Injectable } from '@angular/core';
import { CanActivate, CanActivateChild, Router, ActivatedRouteSnapshot, RouterStateSnapshot, NavigationExtras } from '@angular/router';

// 服务
import { AuthService } from './auth.service';

@Injectable()
export class AuthGuardService implements CanActivate, CanActivateChild {

    constructor(
        private authService: AuthService,
        private router: Router
    ) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        if (state.url && state.url.indexOf('?') > -1) {
            state.url = state.url.substring(0, state.url.indexOf('?'));
        }
        return this.checkLogin(state.url, route.queryParams);
    }

    canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        return this.checkLogin(state.url, childRoute.queryParams);
    }

    // 检查登录
    checkLogin(url: string, queryparams: Object): boolean {
        if (this.authService.isLoggedIn) {
            return true;
        }

        // Set our navigation extras object
        // that contains our global query params and fragment
        const navigationExtras: NavigationExtras = {
            queryParams: queryparams
        };

        // 存储重定向url
        this.authService.redirectURL = url;

        this.router.navigate(['/login'], navigationExtras);
        return false;
    }
}
